/*
* 组件名称：文章详情
* 开发者：scw
* 开发日期：2020-09-12
* 上次修改日期：2020-10-31
* */
import React,{memo, useState, useEffect} from 'react'
import highLight from 'highlight.js'
import marked from 'marked'
import "./style.scss"
import 'highlight.js/styles/monokai-sublime.css'
import { useSelector } from 'react-redux'
import { addFavour, getComments } from "../../pages/api"
import { message } from 'antd'
import Discuss from '../Discuss'

function Detail(props) {
    const {id, author } = props
    const data = useSelector(state => state.articleDetail)
    const [favour, setFavour] = useState(Number(data.favour))
   
    const [commentList, setCommentList] = useState([])
    const renderer = new marked.Renderer();
    marked.setOptions({
        renderer: renderer,
        gfm: true,
        pedantic: false,
        sanitize: false,
        tables: true,
        breaks: false,
        smartLists: true,
        smartypants: false,
        highlight: function (code) {
            return highLight.highlightAuto(code).value;
        }
    });

	const [HTML, setHTMl] = useState(data.content ? marked(data.content) : '')

    useEffect(() => {
        const fetchList = async () => {
            let res = await getComments({ articleId: id })
            if (res.success) {
                setCommentList(res.comments)
            }
        }
        fetchList()
    }, [])

    const addFavourHandle = async () => {
        let res = await addFavour({ id, favour: favour })
        if (res.success) {
            setFavour(res.favour)
            message.success(res.msg)
        } else  {
            message.error(res.msg)
        }
    }

    return (
            <div className="detail">
                <div className={'wacoal'}></div>
                <div className={'detailMain card'}>
                    <div className={'otherMsg'}>
                        <strong className={'title'}>{data.title}</strong>
                        <div className={'date'}>
                            <span>发布时间：{data.create_date?.slice(0, 10)}</span>
                            <span>更新时间：{data.update_date?.slice(0, 10)}</span>
                        </div>
                        <div style={{textAlign: 'center', color: '#cccccc'}}>
                            <span>作者：{author}</span>
                        </div>
                    </div>
                    <div id={'detail'} className={'markedContent'} dangerouslySetInnerHTML={{__html: HTML}}></div>
                    <div className={"good"}>
                        <button type={"button"} onClick={addFavourHandle} className={"ant-btn ant-btn-primary ant-btn-lg"}>
                            <span>点个赞({favour || 0})</span>
                        </button>
                    </div>
                </div>
                <Discuss articleId={id} commentList={commentList} setCommentList={setCommentList} ></Discuss>
            </div>

    )
}

export default memo(Detail)
